<template>
  <common-list>
    <!-- 上-->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        :inline="true"
        @submit.native.prevent
        ref="queryParams"
        label-width="75px"
      >
        <el-form-item label="告警码" prop="alarmCode">
          <common-input
            v-model="queryParams.alarmCode"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="告警等级" prop="alarmLevel">
          <el-select
            v-model="queryParams.alarmLevel"
            style="width: 100%"
            filterable
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="(item, index) in alarmLevelOption"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="告警类型" prop="alarmType">
          <el-select
            v-model="queryParams.alarmType"
            filterable
            clearable
            style="width: 100%"
            @change="alarmTypeChange(queryParams.alarmType)"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="(item, index) in alarmTypeOption"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
<!--
        <el-form-item label="告警子类型" prop="alarmLevel">
          <el-select
            v-model="queryParams.alarmBusiness"
            style="width: 100%"
            filterable
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in sysAlarmBusinessList"
              :key="item.id"
              :label="item.alarmBusiness"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
    </common-search>
    <!-- 中 （三个按钮）-->
    <div slot="tools">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        @click="handleAdd"
        data-test="alarm-code-button-add"
        v-hasPermi="['config:alarmcode:add']"
        >新增</el-button
      >
      <el-button
        type="primary"
        plain
        icon="el-icon-download"
        @click="importShow"
        v-hasPermi="['config:alarmcode:import']"
        >导入</el-button
      >
      <el-button
        type="primary"
        plain
        icon="el-icon-upload2"
        :loading="exportLoading"
        @click="handleExport"
        v-hasPermi="['config:alarmcode:export']"
        >导出</el-button
      >
      <el-button
        type="danger"
        plain
        icon="el-icon-delete"
        @click="handleDelete()"
        v-hasPermi="['config:alarmcode:remove']"
        :disabled="!showBatch"
        >批量删除</el-button
      >
    </div>
    <!--  下 -->
    <common-table
      slot="content"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="告警码"
        align="left"
        prop="alarmCode"
        width="120"
      />
      <el-table-column
        label="告警等级"
        align="left"
        prop="alarmLevel"
        width="100"
      />
      <el-table-column
        label="告警类型"
        align="left"
        prop="alarmType"
        width="100"
      />
      <!-- <el-table-column
        label="告警子类型"
        align="left"
        prop="alarmBusinessName"
        width="120"
      /> -->
      <el-table-column
        label="告警周期"
        align="left"
        prop="alarmPeriod"
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="通知方式"
        align="left"
        prop="noticeTypeString"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="告警模板"
        align="left"
        prop="alarmTemplate"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="操作" align="left" width="90">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['config:alarmcode:edit']"
            data-test="alarm-code-button-edit"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            data-test="alarm-code-button-delete"
            v-hasPermi="['config:alarmcode:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <alarm-dialog
      v-if="dialogShow"
      :visible="dialogShow"
      :title="isEdit"
      :isAlarmCodeManage="true"
      :alarmLevelOption="alarmLevelOption"
      :alarmTypeOption="alarmTypeOption"
      :manuCodeList="manuCodeList"
      :buttonLoading="buttonLoading"
      :noticeTypeList="noticeTypeList"
      @cancel="cancel"
      @submit="submitForm"
      ref="alarmDialog"
    ></alarm-dialog>
    <common-upload-dialog
      download-path="system/alarm/code/downFileByemplateName"
      upload-path="/system/alarm/code/importData"
      template-name="alarmCodeTemplate.xls"
      report-path="system/downErrorReportByemplateName"
      ref="uploadDialog"
      :getList="getList"
    />
  </common-list>
</template>

<script>
import {
  alarmCodeAdd,
  alarmCodeGetAlarmLevel,
  alarmCodeGetAlarmType,
  alarmCodeList,
  alarmCodeEdit,
  alarmCodeGetInfo,
  alarmCodeUsers,
  businessList,
  alarmProductCodes,
  alarmCodeRemove,
  fetchNoticeType,
} from "@/api/system/alarmCode";

import BaseList from "@/mixins/BaseList";
import { sortRule } from "@/utils/formRules";
import { getVendorsList } from "@/api/system/vendors";
import { businessplate_list, user_list } from "@/api/management/system/system";
import loginVue from "../../login.vue";
import Alarm from "../../analysisCenter/assets/components/components/alarm.vue";
import alarmDialog from "./components/alarmDialog/index.vue";
export default {
  mixins: [BaseList],
  code: "index",
  components: {
    alarmDialog,
  },
  data() {
    const checkPath = (rule, value, callback) => {
      const path = new RegExp("^[0-9A-F]{4}$");
      if (path.test(value)) {
        callback();
      } else {
        callback(new Error("请输入( 0-F )4位数"));
      }
    };
    const checkCount = (rule, value, callback) => {
      if (this.form.alarmPeriodType === 0) {
        callback();
      } else {
        if (!value) {
          callback(new Error("请输入告警周期"));
        } else if (value && value < 1) {
          callback(new Error("告警周期不允许小于0"));
        } else {
          callback();
        }
      }
    };
    return {
      exportLoading: false,
      key: "id",
      buttonLoading: false,
      sysAlarmBusinessList: [],
      dialogShow: false, //是否显示
      alarmPeriod: null,
      //查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmLevel: null,
        alarmType: null,
        alarmTime: null,
        alarmBusiness: null,
        alarmCode: null,
      },
      rules: {
        alarmBusiness: [
          {
            required: true,
            message: "请输入告警子类型",
            trigger: "blur",
          },
        ],
        // noticeTypeList: [
        //   { required: true, message: "请选择通知方式", trigger: "blur" },
        // ],
        // noticeUsers: [
        //   { required: true, message: "请选择通知人", trigger: "blur" },
        // ],
        alarmPeriodCount: [
          { min: 1, required: true, validator: checkCount, trigger: "blur" },
        ],
        manuCode: [
          {
            required: true,
            message: "请选择厂商编码",
            trigger: "blur",
          },
        ],
        systemCode: [
          {
            required: true,
            message: "请选择系统编码",
            trigger: "blur",
          },
        ],
        alarmCodeNum: [
          {
            required: true,
            message: "请输入告警码",
            trigger: "blur",
          },
          { required: true, validator: checkPath, trigger: "blur" },
        ],
        alarmContent: [
          {
            required: true,
            message: "请输入告警内容",
            trigger: "blur",
          },
        ],
        alarmLevel: [
          {
            required: true,
            message: "请选择告警等级",
            trigger: "blur",
          },
        ],
        alarmType: [
          {
            required: true,
            message: "请选择告警类型",
            trigger: "blur",
          },
        ],
        orderNum: sortRule,
      },
      loading: false,
      account: "",
      list: [],
      warningOpen: false,
      disabled: true,
      systemCodeList: [],
      alarmLevelOption: [], //告警等级
      alarmTypeOption: [], //告警类型
      manuCodeList: [],
      isDisabled: false,
      alarmPeriodCount: "",
      // 已选择的通知人
      businessPlateCheckedId: null, // 流程id
      isEdit: false, // 是否编辑状态
      businessPlateList: [],
      form: {
        alarmBusiness: "",
        manuCode: "",
        alarmCodeNum: "",
        systemCode: "",
        id: "",
        alarmCode: "", //告警码
        alarmContent: "", //告警内容
        alarmLevel: "", //告警等级
        alarmType: "", //告警类型
        noticeContent: "",
        remark: "", //备注
        noticeTypeList: [], // 通知方式
        noticeUsers: [],
        alarmPeriodType: 0,
        alarmPeriodCount: 0,
      },
      total: 0,
      userList: [], // 用户列表

      defaultContent: [
        {
          noticeType: "workOrder", // 工单: workOrder 系统消息: message 邮件: email 短信: sms
          checked: 0, // 0: 选中 1: 未选中
          account: "", // deploymentId,name,key
        },
        { noticeType: "message", checked: 0, account: "" },
        { noticeType: "email", checked: 0, account: "" },
        { noticeType: "sms", checked: 0, account: "" },
      ],
      noticeTypeList: [],
    };
  },
  created() {
    this.getNoticeType();
    Promise.all([this.getAlarmLevel(), this.getAlarmType()]).then((res) => {
      this.alarmLevelOption = res[0];
      this.alarmTypeOption = res[1];
      this.getManuCodeList();
      // this.getBusinessPlateList();
      this.getList();
      this.alarmTypeChange();
    });
  },
  methods: {
    // alarmPeriodCountChange(row) {
    //   if (row === 0) {
    //     this.form.alarmPeriodCount = 0;
    //   }
    // },

    getNoticeType() {
      fetchNoticeType().then((res) => {
        if (res && res.code === 200) {
          this.noticeTypeList = res.data;
        }
      });
    },

    alarmTypeChange(row) {
      businessList({ alarmType: row }).then((res) => {
        if (res && res.code === 200) {
          this.sysAlarmBusinessList = res.rows;
        } else {
          this.sysAlarmBusinessList = [];
        }
        this.queryParams.alarmBusiness = null;
      });
    },

    // manCode(res) {
    //   this.alarmProductCodes(res);
    //   this.form.systemCode = "";
    // },
    importShow() {
      this.$refs.uploadDialog.show();
    },

    handleExport() {
      //导出
      this.exportLoading = true;
      this.download(
        "system/alarm/code/export",
        {
          pageNum: 1,
          pageSize: 10000,
          selectedIds: this.ids.join(","),
        },
        `alarmCode_${new Date().getTime()}.xlsx`
      ).finally(() => {
        this.exportLoading = false;
      });
    },

    // getBusinessPlateList() {
    //   businessplate_list({ businessPlate: "0" }).then((res) => {
    //     this.businessPlateList = res.result;
    //   });
    // },
    getList() {
      this.loading = true;
      alarmCodeList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows.reduce((r, c) => {
              let alarmLevel = this.getAlarmLevelNameById(c.alarmLevel);
              let alarmType = this.getAlarmTypeNameById(c.alarmType);
              let alarmPeriod = null;
              if (c.alarmPeriodType === 0) {
                alarmPeriod = null;
              }
              if (c.alarmPeriodType === 1) {
                alarmPeriod = "每天告警" + c.alarmPeriodCount + "次";
              }
              if (c.alarmPeriodType === 2) {
                alarmPeriod = "每小时告警" + c.alarmPeriodCount + "次";
              }

              if (c.alarmNotice) {
                let noticeTypes = JSON.parse(c.alarmNotice);
                let noticeTypes2 = [];

                if (!noticeTypes[0]) {
                  noticeTypes.splice(0, 1);
                }
                let checkedNoticeTypes = noticeTypes.filter((item) => {
                  return item.checked === 0;
                });
                checkedNoticeTypes.forEach((item) => {
                  this.noticeTypeList.forEach((noticeData) => {
                    if (noticeData.value === item.noticeType) {
                      item.noticeTypeTemp = noticeData.label;
                    }
                  });

                  noticeTypes2.push(item.noticeTypeTemp);
                });
                c.noticeTypeString = noticeTypes2.join();
              }

              r.push({
                ...c,
                alarmLevel,
                alarmType,
                alarmPeriodCount: c.alarmPeriodCount.toString(),
                alarmPeriod: alarmPeriod,
              });
              return r;
            }, []);
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    getAlarmLevelNameById(id) {
      let al = this.alarmLevelOption.find(
        (item) => parseInt(item.id) === parseInt(id)
      );
      return al ? al.name : "";
    },
    getAlarmTypeNameById(id) {
      let at = this.alarmTypeOption.find(
        (item) => parseInt(item.id) === parseInt(id)
      );
      return at ? at.name : "";
    },

    reset() {
      this.form = this.$options.data().form;
    },
    getAlarmLevel() {
      return new Promise((resolve, reject) => {
        alarmCodeGetAlarmLevel().then((res) => {
          if (res && res.code === 200) {
            resolve(res.data);
          } else {
            this.alarmLevelOption = [];
            reject(res);
          }
        });
      });
    },
    getAlarmType() {
      return new Promise((resolve, reject) => {
        alarmCodeGetAlarmType().then((res) => {
          if (res && res.code === 200) {
            resolve(res.data);
          } else {
            this.alarmTypeOption = [];
            reject(res);
          }
        });
      });
    },

    // 查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 新增按钮
    handleAdd() {
      this.dialogShow = true;
      this.isEdit = false;
      this.$nextTick(() => {
        this.$refs.alarmDialog.handleAdd();
      });
    },
    // 取消
    cancel() {
      this.dialogShow = false;
      // this.reset();
      this.manuCode = "";
      this.alarmCode = "";
      this.systemCode = "";
      this.form.noticeUsers = [];
      this.form.noticeTypeList = [];
      this.businessPlateCheckedId = "";
    },
    //编辑
    handleUpdate(row) {
      this.isEdit = true;
      this.dialogShow = true;
      this.$nextTick(() => {
        this.$refs.alarmDialog.handleUpdate(row);
      });
    },
    //删除
    handleDelete(row) {
      const ids = row?.id || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          alarmCodeRemove({ ids }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                ids.split(",").length === this.list.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 确定按钮
    submitForm(form) {
      // if (

      //   (this.form.noticeUsers.length === 0 &&
      //     this.form.noticeTypeList.length === 0) ||
      //   (this.form.noticeUsers.length !== 0 &&
      //     this.form.noticeTypeList.length !== 0)
      // ) {
      //   this.form.alarmCode =
      //     this.form.manuCode + this.form.systemCode + this.form.alarmCodeNum;
      //   let noticeContent = this.defaultContent.reduce((r, c) => {
      //     if (c.noticeType === "workOrder") {
      //       if (this.businessPlateCheckedId) {
      //         let obj = this.businessPlateList.find(
      //           (item) => item.key === this.businessPlateCheckedId
      //         );

      //         r.push({
      //           noticeType: c.noticeType,
      //           checked: 0,
      //           account: `${obj.deploymentId},${obj.name},${obj.key}`,
      //         });
      //       } else {
      //         if (this.businessPlateList.length == 0) {
      //           r.push(this.account);
      //         } else {
      //           r.push({
      //             noticeType: c.noticeType,
      //             checked: 1,
      //             account: "",
      //           });
      //         }
      //       }
      //     } else {
      //       let checked = this.form.noticeTypeList.includes(c.noticeType);
      //       r.push({
      //         noticeType: c.noticeType,
      //         checked: checked ? 0 : 1,
      //         account: checked ? this.form.noticeUsers.join(",") : "",
      //       });
      //     }

      //     return r;
      //   }, []);
      //   this.$refs["form"].validate((valid) => {
      //     if (valid) {
      this.buttonLoading = true;
      if (this.isEdit) {
        //编辑有id(如果id不为空）
        alarmCodeEdit(form)
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("编辑成功");
              this.dialogShow = false;
              this.getList();
            } else {
              this.$GlobalErrorConfirm("编辑失败", res.msg);
            }
          })
          .finally(() => {
            this.buttonLoading = false;
          });
      } else {
        alarmCodeAdd(form)
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("新增成功");
              this.dialogShow = false;
              this.getList();
            } else {
              this.$GlobalErrorConfirm("新增失败", res.msg);
            }
          })
          .finally(() => {
            this.buttonLoading = false;
          });
      }
      //     }
      //   });
      // } else {
      //   if (this.form.noticeUsers.length === 0) {
      //     this.$GlobalErrorConfirm("提示", "请选择通知人");
      //   } else {
      //     this.$GlobalErrorConfirm("提示", "请选择通知方式");
      //   }
      // }
    },
    // 重置
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    getManuCodeList() {
      getVendorsList().then((res) => {
        this.manuCodeList = res.rows;
      });
    },
    // alarmProductCodes(res) {
    //   alarmProductCodes({ manuCode: res }).then((res) => {
    //     this.systemCodeList = res.data;
    //   });
    // },
  },
};
</script>

<style scoped lang="scss"></style>
